<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of report
 *
 * @author Константин Охотник
 */
class ClientModel extends Crud
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('ci_access');
    }
 
/*===============================Вывод всех регионов===============================*/   
    public function Region()
    {
        $rez = $this->get_one('region','country_id', '9908');
        $list_city = array();
        $i =0;
        foreach ($rez as $key => $val)
        {
            $k = $rez[$key]['region_id'];
            $list_city[$i]['region'] = $rez[$key]['name'];
            $list_city[$i]['region_id'] = $k;
            $i++;
        }
        return $list_city;
    }
    
/*===============================Вывод всех городов===============================*/   
    public function City($region)
    {
        $rez = $this->get_one('city','region_id', $region['id_region']);
        $list_city = array();
        $i =0;
        foreach ($rez as $key => $val)
        {
            $k = $rez[$key]['region_id'];
            $list_city[$i]['region'] = $rez[$key]['name'];
            $list_city[$i]['region_id'] = $k;
            $i++;
        }
        return $list_city;
    }
    
/*===============================Вывод всех клиентов===============================*/
    public function getClient($url, $per_page)
    {
        $config['base_url']   = $url;
        $config['total_rows'] = $this->db->count_all('tb_client');
        $config['per_page']   = $per_page;
        $this->pagination->initialize($config);
        $r = $this->db->query('SELECT * FROM tb_client order by id desc LIMIT '.(int)$this->uri->segment(3).', '. (int)$config['per_page'].' ');
        $i = 0;
        foreach($r =$r->result_array() as $key )
        {
           $p = $this->get_one('tb_person', 'id', $key['id_person']);
           if(empty($p))
           {
               $r[$i]['id_person'] = 'Пользователь удалён';
           }
           else
           {
               $r[$i]['id_person'] = $p[0]['name'].' '.$p[0]['first_name'].' '.$p[0]['second_name'];
           }
           $i++;
        }
        return $r;
    }
    
/*===============================Удаление клиента===============================*/    
    public function Delete($cell)
    {
        $this->delete_post('tb_client', 'id', $cell);
    }

/*==============================Добавление нового клиента=======================*/     
    public function Add($arr)
    {
        
        $arr['id_person'] = $_SESSION['userdata'][1];
        $region = $this->get_one('region','region_id',$arr['region']);
        $arr['region']=$region[0]['name'];
        return $this->add_db('tb_client', $arr);
    }
    
/*===================================Вывод сайтов==============================*/
    public function GetSite()
    {
        return $this->get_array('gl_site');
    }
    
/*===================================Поиск клиента==============================*/      
    public function Filter($url, $request, $per_page)
    {
        $offers = 0;                                //Для limit $offers, $num
        foreach($request as $key=>$value)
        {
            if($value =="")
            {
                unset($request[$key]);
            }
        }
        $selcount =  $this->_CountRowsQuery('SELECT COUNT(*) FROM tb_client WHERE ', $request);
        $seldata  =  $this->_CountRowsQuery('SELECT * FROM tb_client WHERE ', $request);
        $num_rows = $this->numRowsTender($selcount);
        if($num_rows == 0)
        {
            $query['error'] = "По вашему запросу ничего не найдено";
            return $query;
        }
        $config['base_url']=$url.'?'.http_build_query($request);
        $config['total_rows'] = $num_rows;
        $config['per_page'] = $per_page;
        $config['page_query_string'] = TRUE;
        $this->pagination->initialize($config);
        $query = $this->_getFilterTenders($seldata, $config['per_page'],$offers);
        return  $query;
    }

/*===================================Построение запроса==========================*/     
    private function _CountRowsQuery($select, $request)
    {
        $idcategory="";
        $count = 0;
        foreach($request as $key =>$value)
        {
            if ($key =='category')
            {
                $this->_param['id_tndcategory'] = $request[$key];
                $idcategory = $this->get_one('gl_ant_tndrcategory', 'category', $request[$key]);
                $select.="  id_tndcategory = ".$idcategory[0]['id_category'];
            }
            if($key == 'name')
            {
                $select.= " name LIKE '%".$request[$key]."%'";
            }
            if($key == 'phone')
            {
                $select.= " phone LIKE '%".$request[$key]."'";
            }
            if($key == 'id_site')
            {
                $select.= " id_site = '".$request[$key]."'";
            }
            if ($count <(count($request)-1))
            {
                $select.=" AND ";
            }
            $count++;
        }
        return $select;
    }
    
/*===================================Кол записей=============================*/      
    private function numRowsTender($str)
    {
        $query= $this->db->query($str)->result();
        $arr =(array)$query[0];
        return (integer)$arr['COUNT(*)'];
    }
    
/*===================================Вывод==================================*/       
    private function _getFilterTenders($select, $num, $offset= 0)
    {
        $offset = (int)$offset;
        $select .= " ORDER BY id DESC LIMIT  $offset , $num";
        $query = $this->db->query($select);
        $r = $query->result_array();
        foreach ($r as $key=>$value)
        {
           $p = $this->get_one('tb_person', 'id', $value['id_person']);
           if(empty($p))
           {
               $r[$key]['id_person'] = 'Пользователь удалён';
           }
           else
           {
               $r[$key]['id_person'] = $p[0]['name'].' '.$p[0]['first_name'].' '.$p[0]['second_name'];
           }
        }
        return $r;
    }
    
}